xquery version "0.9-ml"

module "http://www.marklogic.com/ps/lib/lib-session"
declare namespace s="http://www.marklogic.com/ps/lib/lib-session"

import module namespace io = "com.marklogic.developer.cq.io" at "/lib/lib-io.xqy"

(: we don't want to have to prefix the fn:* functions :)
default function namespace = "http://www.w3.org/2003/05/xpath-functions"

define variable $s:SESSION-RELPATH as xs:string { "data/" }

define variable $s:SESSION-DIRECTORY as xs:string {
  let $path := xdmp:get-request-path()
  (: ensure that the path ends with "/" :)
  let $path :=
    if (ends-with($path, "/"))
    then $path
    else concat(
      string-join(tokenize($path, "/")[ 1 to last() - 1], "/"), "/"
    )
  let $dir := concat($path, $s:SESSION-RELPATH)
  let $log := xdmp:log(text{"SESSION-DIRECTORY:",$dir})
  return $dir
}

define variable $s:CONFIG as element(config) {
  let $path := concat($s:SESSION-DIRECTORY, "services.xml")
  let $read := io:read($path)
  where io:exists($path)
  return $read/services/config
}

define variable $s:SERVICES as element(service)* {
  let $path := concat($s:SESSION-DIRECTORY, "services.xml")
  let $read := io:read($path)
  where io:exists($path)
  return $read/services/service
}

define function s:save-session($session) as empty() {
  io:write(concat($s:SESSION-DIRECTORY, "xxx.xml"), document { $session })
}

define function s:get-queries($service as xs:string) {
	$s:SERVICES[name = $service]/queries/query
}

define function s:get-query($service as xs:string, $query as xs:string) {
	$s:SERVICES[name = $service]/queries/query[@name = $query]	
}
